package com.test.auth_db_auto.filter;

import com.test.auth_db_auto.exception.AuthFailureException;
import com.test.auth_db_auto.support.BootSecurityProperties;
import com.test.auth_db_auto.support.code.BootCodeService;
import com.test.auth_db_auto.support.properities.BootBaseLoginProperties;
import io.micrometer.core.instrument.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ Author: .Mr
 * @ ClassName BootPictureCodeAuthenticationFilter
 * @ Description TODO
 * @ date 2021/12/30 11:16
 * @ Version 1.0
 * 图像码验证
 */
public class BootPictureCodeAuthenticationFilter extends OncePerRequestFilter {

    private AntPathMatcher pathMatcher=new AntPathMatcher();
    private BootSecurityProperties properties;
    private BootCodeService<String> bootCodeService;
    private AuthenticationFailureHandler handler;

    public BootPictureCodeAuthenticationFilter(BootSecurityProperties properties,BootCodeService<String> bootCodeService,AuthenticationFailureHandler handler){
        this.properties=properties;
        this.bootCodeService=bootCodeService;
        this.handler=handler;

    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        //本次请求的路径
        String path=request.getRequestURI();
        BootBaseLoginProperties baseLogin = this.properties.getBaseLogin();

        if(pathMatcher.match(baseLogin.getLoginProcessUrl(),path)){ // 路径匹配判断
            //图片验证码值
            String pCode=request.getParameter(baseLogin.getPictureCodeParameterName());
            String key=request.getParameter("key");

            if(StringUtils.isBlank(pCode)){
                request.setAttribute("error","error");
                this.handler.onAuthenticationFailure(request,response,new AuthFailureException("验证码错误"));
                return;
            }
            if(!this.bootCodeService.verification(key,pCode,true)){
                this.handler.onAuthenticationFailure(request,response,new AuthFailureException("验证码错误"));
                return;
            }
        }

        chain.doFilter(request,response);
    }
}
